package com.zmn.brs.admin.controller.scene;

import com.zmn.brs.business.interfaces.objective.ObjectiveTargetJobBService;
import com.zmn.brs.common.constant.RedisKeyConst;
import com.zmn.brs.common.enums.SceneTypeEnum;
import com.zmn.brs.model.entity.scene.Scene;
import com.zmn.brs.model.entity.scene.SceneQuery;
import com.zmn.brs.services.interfaces.scene.SceneService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.dictionary.StatusEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 业务场景配置
 * @author chongw
 * @since 2021-05-27
 **/
@Controller
@RequestMapping(value = "/brs/scene/")
public class SceneModifyController extends SceneBaseController {

    @Resource
    private SceneService sceneService;

    @Resource
    private ObjectiveTargetJobBService objectiveTargetJobBService;

    @Resource
    RedisTemplate<String, Integer> redisTemplate;

    /**
     * 描述: 修改业务场景
     * @param vo 业务场景
     * @return com.zmn.common.dto.ResultDTO
     **/
    @ResponseBody
    @RequestMapping(value = "modifyScene")
    public ResponseDTO modifyScene(@RequestBody Scene vo) {
        try {
            if(NumberUtil.isNullOrZero(vo.getSceneId())){
                return ResponseDTO.fail("场景ID不能为空");
            }
            Scene scene = sceneService.findById(vo.getSceneId());
            if(scene == null){
                return ResponseDTO.fail("未找到场景信息");
            }
            //判断是否是绩效监控场景，如果是绩效监控，则校验以下数据必填
            if(SceneTypeEnum.TARGET.getTypeId().equals(scene.getType())){
                if(StringUtil.isBlank(vo.getMonitorCycle())){
                    return ResponseDTO.fail("监控周期不能为空");
                }
                if(StringUtil.isBlank(vo.getComputeTime())){
                    return ResponseDTO.fail("指标计算时间不能为空");
                }
                if(StringUtil.isBlank(vo.getPushTime())){
                    return ResponseDTO.fail("指标推送时间不能为空");
                }
                if(!DateUtil.isValid(vo.getComputeTime(),"HH:mm:ss")){
                    return ResponseDTO.fail("指标计算时间格式有误！");
                }
                if(!DateUtil.isValid(vo.getPushTime(),"HH:mm:ss")){
                    return ResponseDTO.fail("指标推送时间格式有误！");
                }
            }
            scene.setUpdater(super.getMcStaffRealName());
            scene.setUpdateTime(DateUtil.getNow());
            scene.setSceneName(vo.getSceneName());
            scene.setRemarks(vo.getRemarks());
            scene.setMonitorCycle(vo.getMonitorCycle());
            scene.setComputeTime(vo.getComputeTime());
            scene.setPushTime(vo.getPushTime());
            Integer falg = sceneService.updateByKey(scene);
            if(falg > 0){
                if(SceneTypeEnum.TARGET.getTypeId().equals(scene.getType())) {
                    objectiveTargetJobBService.refreshJob(SceneQuery.builder()
                        .sceneId(scene.getSceneId())
                        .build());
                }
                return ResponseDTO.success(true,"业务场景修改成功！");
            }
            return ResponseDTO.fail("业务场景修改失败！");
        } catch (Exception e) {
            logger.error("业务场景修改异常，异常信息：" + e);
            return ResponseDTO.fail("业务场景修改异常！");
        }
    }

    /**
     * 启用场景
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("enable")
    public ResponseDTO enable(@RequestParam(value = "ids") List<Integer> ids){
        if(ids.isEmpty()) return ResponseDTO.fail("请选择需要启用的数据！");
        //批量修改规则状态
        Integer flag = this.modifyStatus(ids, StatusEnum.ENABLE.getCode());
        if(flag > 0){
            return ResponseDTO.success(null,"启用成功！");
        }
        return ResponseDTO.fail("启用失败！");
    }

    /**
     * 停用场景
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("disable")
    public ResponseDTO disable(@RequestParam(value = "ids") List<Integer> ids){
        if(ids.isEmpty()) return ResponseDTO.fail("请选择需要停用的数据！");
        //批量修改规则状态
        Integer flag = this.modifyStatus(ids,StatusEnum.DISABLE.getCode());
        if(flag > 0){
            return ResponseDTO.success(null,"停用成功！");
        }
        return ResponseDTO.fail("停用失败！");
    }

    /**
     * 修改场景状态
     * @param sceneIdList
     * @param status
     * @return
     */
    private Integer modifyStatus(List<Integer> sceneIdList,Integer status){
        //设置需要修改的属性值
        List<Scene> sceneList = sceneIdList.stream().map(o->{
            Scene scene = new Scene();
            scene.setSceneId(o);
            scene.setStatus(status);
            scene.setUpdater(super.getMcStaffRealName());
            scene.setUpdateTime(DateUtil.getNow());
            return scene;
        }).collect(Collectors.toList());
        Integer flag = sceneService.updateBatchByKey(sceneList);
        if(flag > 0){
            sceneIdList.stream().forEach(o -> {

                String redisKey = RedisKeyConst.getStatusRedisKey(RedisKeyConst.SCENE_STATUS_REDIS_KEY, o);
                redisTemplate.opsForValue().set(redisKey, status);

                objectiveTargetJobBService.initJob(SceneQuery.builder()
                    .sceneId(o)
                    .build());
            });
        }
        return flag;
    }

}
